package com.hmdp.error;

import cn.hutool.core.io.resource.ResourceUtil;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 大忽悠
 * @create 2022/4/20 10:29
 */
public class ErrorMsgHandler {
    /**
     * 放到classPath下
     */
    private static final String ERR_PROPERTIES_PATH="err.properties";

    /**
     * 错误的配置文件
     */
    private static final Properties ERR_PROPERTIES=new Properties();

    /**
     * 错误消息分隔符
     */
    private static final String ERR_MSG_SEPARATOR=".";

    /**
     * 错误信息的缓存,防止每次都去进行IO读取操作
     */
    private  static Map<String,String> errMsgCache;

    static {
        try {
            //资源判断是否存在
            InputStream errInputStream = ErrorMsgHandler.class.getClassLoader().getResourceAsStream(ERR_PROPERTIES_PATH);
            ERR_PROPERTIES.load(errInputStream);
        } catch (IOException e) {
            System.err.println(ERR_PROPERTIES_PATH+" is not exist!");
        }
    }

    /**
     * 通过错误key拿到错误msg
     */
    public static String getErrMsg(String num,Class targetClass)
    {
        String errKey = targetClass.getName() + ERR_MSG_SEPARATOR + num;
        //先尝试从缓存中获取
        if(errMsgCache!=null&&errMsgCache.containsKey(errKey))
        {
            return errMsgCache.get(errKey);
        }
        String errMsg = ERR_PROPERTIES.getProperty(errKey);
        validProperty(errKey,errMsg);
        return errMsg;
    }

    /**
     * 对获得到的property进行校验
     */
    private static void validProperty(String errKey,String errMsg) {
        if(errMsg ==null|| errMsg.isEmpty())
        {
            throw new IllegalArgumentException("err msg get fail,maybe num is invalid or targetClass is error");
        }
        //懒加载
        errMsgCache=new ConcurrentHashMap<>();
        errMsgCache.put(errKey,errMsg);
    }


}
